<template>
  <div>
    <!-- 可拖动的图标 -->
    <div
      class="draggable-box"
      :style="{ top: position.y + 'px', left: position.x + 'px' }"
      @mousedown="startDrag"
      @mousemove="onDrag"
      @mouseup="stopDrag"
      @click="showChatModalState"
    >
      <img src="./fox.png" style="width: 75px; pointer-events: none" />
    </div>

    <!-- 聊天侧边栏 -->
    <div v-if="showChatModal" class="modal-overlay">
      <div class="modal">
        <div class="chat-header">
          <div class="welcome-message">欢迎使用</div>
          <button class="close-button" @click="showChatModalState">×</button>
        </div>
        <div :class="['chat-container', { 'expanded': showHistory }]">
          <!-- 历史会话列表 -->
          <div v-if="showHistory" class="sidebar">
            <div class="header">
              <button class="exit-button" @click="toggleHistory">退出历史记录</button>
            </div>
            <div ref="messagesContainer1" class="history-list">
              <div v-for="(session, index) in sessions" :key="index" class="history-item" @click="loadSession(session)">
                <div class="session-details">
                  <div class="session-name">{{ session.name }}</div>
                  <div class="session-time">{{ session.createdTime }}</div>
                </div>
                <button class="delete-button" @click.stop="deleteSession(session.id)">删除</button>
              </div>
            </div>
          </div>
          <!-- 主聊天区域 -->
          <div v-else class="main">
            <div class="main-content">
              <div ref="messagesContainer" class="messages">
                <div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
                  <div v-if="message.type === 'server'" class="server-label">
                    <img src="./fox.png" alt="图标" class="icon" />
                    <span class="label-text">擎小天</span>
                  </div>
                  <span class="text" v-html="message.text"></span>
                </div>
              </div>
              <div style="border-top: 1px solid #e0e0e0"></div>
              <div>
                <img src="./time.svg" alt="描述文字" style="width: 24px; height: 24px; margin-left: 10px; margin-top: 10px" @click="toggleHistory" />
                <img src="./add.svg" alt="描述文字" style="width: 24px; height: 24px; margin-left: 10px" @click="createNewSession" />
              </div>
              <div class="controls">
                <textarea
                  v-model="userInput"
                  placeholder="请输入内容，按回车发送信息"
                  rows="4"
                  style="resize: none; width: 100%"
                  @keyup.enter="sendMessage"
                ></textarea>
                <img src="./send.svg" alt="发送" class="send-icon" @click="sendMessage" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { EventSourcePolyfill } from 'event-source-polyfill';

export default {
  data() {
    return {
      position: { x: 1300, y: 700 }, // 初始位置
      isDragging: false, // 是否正在拖动
      isMenuOpen: false, // 菜单是否打开
      initialX: 0, // 初始鼠标 X 坐标
      initialY: 0, // 初始鼠标 Y 坐标
      wasDragging: false, // 是否曾经拖动过

      showChatModal: false, // 是否显示聊天模态框
      sessions: [], // 存储历史会话
      currentSession: null, // 当前选中的会话
      messages: [], // 消息列表
      userInput: '', // 用户输入
      eventSource: null, // 用于接收服务器事件的 EventSource 对象
      checked1: 0, // 用于控制连续对话的开关
      showHistory: false // 控制历史记录显示的状态
    };
  },
  mounted() {
    this.loadSessions(); // 加载历史会话
    this.scrollToBottom(); // 滚动到底部

    // 新增部分：初始化时添加一条欢迎消息
    this.messages.push({ type: 'server', text: '你好，有什么可以帮到你呢？' });
    this.scrollToBottom();
  },
  beforeUnmount() {
    // 确保在组件销毁前移除所有事件监听器
    document.removeEventListener('mousemove', this.onDrag);
    document.removeEventListener('mouseup', this.stopDrag);
  },
  methods: {
    //点击鼠标
    startDrag(e) {
      this.isDragging = true;
      this.initialX = e.clientX - this.position.x;
      this.initialY = e.clientY - this.position.y;
      // 添加全局事件监听器
      document.addEventListener('mousemove', this.onDrag);
      document.addEventListener('mouseup', this.stopDrag);
    },
    //鼠标移动
    onDrag(e) {
      if (this.isDragging) {
        this.wasDragging = true; // 标记为正在拖动
        this.updatePosition(e.clientX, e.clientY);
      }
    },
    updatePosition(clientX, clientY) {
      const newX = clientX - this.initialX;
      const newY = clientY - this.initialY;

      // 使用 requestAnimationFrame 来平滑动画
      requestAnimationFrame(() => {
        this.position.x = newX;
        this.position.y = newY;
        this.showChatModal = false; // 位置变化时隐藏菜单
      });
    },
    //抬起鼠标
    stopDrag() {
      this.isDragging = false;
      // 移除全局事件监听器
      document.removeEventListener('mousemove', this.onDrag);
      document.removeEventListener('mouseup', this.stopDrag);
    },
    loadSessions() {
      /*  const token = localStorage.getItem('Admin-Token'); // 获取 token*/
      // 从后端加载历史会话
      fetch(
        'http://localhost/dev-api/system/sessions/list'
        /*       , {
        headers: {
          'Authorization': `Bearer ${token}` // 设置 Authorization 头
        }
        }*/
      )
        .then((response) => response.json())
        .then((data) => {
          this.sessions = data.rows.map((session) => ({
            id: session.sessionId, // 使用 sessionId 作为 id
            name: session.sessionName, // 使用 sessionName 作为 name
            createdTime: session.createdAt // 假设后端返回的会话对象包含 createdAt 字段
          }));
          // 加载完会话后滚动到底部
          this.scrollToBottom1();
        })
        .catch((error) => console.error('Error loading sessions:', error));
    },
    // 加载完会话后滚动到底部
    scrollToBottom1() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer1;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },
    loadSession(session) {
      this.showHistory = !this.showHistory;
      this.currentSession = session;
      this.messages = [];

      // 从后端加载当前会话的消息
      fetch(`http://localhost/dev-api/system/messages/list?sessionId=${session.id}`)
        .then((response) => response.json())
        .then((data) => {
          this.messages = data.rows.map((msg) => ({
            type: msg.sender === '0' ? 'user' : 'server',
            text: msg.content,
            finished: true
          }));
        })
        .catch((error) => console.error('Error loading messages:', error));

      this.scrollToBottom();
    },
    showChatModalState() {
      // 只有在没有拖动的情况下点击才显示菜单
      if (!this.wasDragging) {
        this.showChatModal = !this.showChatModal;
      }
      this.wasDragging = false; // 重置拖动标志
      this.showHistory = false;
    },
    createNewSession() {
      // 创建新的会话
      fetch('http://localhost/dev-api/system/sessions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          sessionName: '新会话' + new Date().getTime(),
          isContinuous: this.checked1,
          maxHistoryLength: 1000
        })
      })
        .then((response) => response.json())
        .then((data) => {
          this.currentSession = {
            id: data.data.sessionId,
            name: data.data.sessionName,
            createdTime: data.data.createdAt
          };
          this.messages = [];
          this.loadSessions(); // 刷新历史会话列表
        })
        .catch((error) => console.error('Error creating session:', error));
    },
    initEventSource(message = '') {
      if (this.eventSource) {
        // 如果已经存在 EventSource，则先关闭
        this.eventSource.close();
      }

      const token = localStorage.getItem('Admin-Token'); // 获取 token

      const url = new URL('http://localhost/dev-api/sse/test');
      if (message) {
        url.searchParams.append('message', message);
      }
      if (this.currentSession && this.currentSession.id) {
        url.searchParams.append('sessionId', this.currentSession.id); // 新增这一行
      }

      // 使用 fetch 模拟 EventSource
      const eventSource = new EventSourcePolyfill(url.href, {
        headers: {
          'Authorization': `Bearer ${token}` // 设置 Authorization 头
        }
      });

      this.eventSource = eventSource;

      this.eventSource.onmessage = (evt) => {
        const data = JSON.parse(evt.data);
        const lastServerMessage = this.messages.find((m) => m.type === 'server' && !m.finished);

        if (lastServerMessage) {
          // 更新最后一个未完成的服务器消息，并在适当位置插入换行符
          lastServerMessage.text += data.text.replace(/\n/g, '<br>');
        } else {
          // 新增一个服务器消息
          this.messages.push({ type: 'server', text: data.text.replace(/\n/g, '<br>'), finished: false });
        }

        // 检查 finish_reason 是否为 stop
        if (data.finish_reason === 'stop') {
          this.eventSource.close();
          const lastServerMessageIndex = this.messages.findIndex((m) => m.type === 'server' && !m.finished);
          if (lastServerMessageIndex !== -1) {
            this.messages[lastServerMessageIndex].finished = true;
          }
          // 如果 sessionId 为空且 data 中有 sessionId，更新 currentSession
          if (!this.currentSession && data.sessionId) {
            this.currentSession = {
              id: data.sessionId
            };
          }
        }

        // 自动滚动到底部
        this.scrollToBottom();
      };

      // 处理错误
      this.eventSource.onerror = (err) => {
        console.error('EventSource failed:', err);
        this.eventSource.close();
      };
    },

    showChatModalClose() {
      this.showChatModal = false;
      this.showHistory = false;
    },
    sendMessage() {
      if (!this.userInput.trim()) {
        alert('请输入消息');
        return;
      }

      // 添加用户消息到消息列表
      this.messages.push({ type: 'user', text: this.userInput });

      // 使用相同的 EventSource URL 并附带消息参数
      this.initEventSource(this.userInput);

      // 清空输入框
      this.userInput = '';

      // 自动滚动到底部
      this.scrollToBottom();
    },
    deleteSession(sessionId) {
      const token = Cookies.get('Admin-Token'); // 获取 token
      // 发送请求删除会话
      fetch(`http://localhost/dev-api/system/sessions/${sessionId}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}` // 设置 Authorization 头
        }
      })
        .then((response) => {
          if (response.ok) {
            // 删除成功后，更新会话列表
            this.loadSessions();
            if (this.currentSession && this.currentSession.id === sessionId) {
              // 如果当前会话被删除，清空消息列表
              this.messages = [];
              this.currentSession = null;
            }
          } else {
            console.error('Error deleting session:', response.statusText);
          }
        })
        .catch((error) => console.error('Error deleting session:', error));
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },
    toggleHistory() {
      this.showHistory = !this.showHistory; // 切换历史记录的显示状态
    }
  }
};
</script>

<style scoped>
.exit-button {
  background-color: #e84b4e;
  color: #fff;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
  width: 100%; /* 按钮宽度占满整个历史记录项 */
  text-align: center; /* 按钮文本居中对齐 */
}
.add-button {
  background: #000000;
  border: none;
  font-size: 24px;
  color: #333;
  cursor: pointer;
}
/*关闭按钮*/
.close-button {
  background: none;
  border: none;
  font-size: 30px;
  color: #999;
  cursor: pointer;
}

/*文字和图片*/
.server-label {
  display: flex;
  align-items: center;
  margin-bottom: 5px; /* 可以根据需要调整间距 */
}

.server-label .icon {
  width: 20px; /* 图标的宽度 */
  height: 20px; /* 图标的高度 */
  margin-right: 5px; /* 图标和文字之间的间距 */
}

.server-label .label-text {
  font-size: 14px; /* 文字大小 */
  color: #333; /* 文字颜色 */
}

/* 侧边栏容器 */
.modal-overlay {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  width: 300px;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: flex-end;
  align-items: center;
  z-index: 1000;
}

.modal {
  width: 100%;
  height: 100%;
  background-color: #fff;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-message {
  font-size: 18px;
  font-weight: bold;
}

.chat-container {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  overflow: hidden;
}

.sidebar {
  width: 300px;
  border-right: 1px solid #e0e0e0;
  overflow-y: auto;
}

.history-list {
  padding: 10px;
}

.history-item {
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.session-details {
  display: flex;
  flex-direction: column;
}

.session-name {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 10px;
}

.session-time {
  font-size: 14px;
  color: #777;
}

.delete-button {
  background-color: #e84b4e;
  color: #fff;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
}

.main {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.main-content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.messages {
  flex-grow: 1;
  padding: 20px;
  overflow-y: auto;
}

.message {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 4px;
}

.message.user {
  background-color: #e0e0e0;
  align-self: flex-end;
}

.message.bot {
  background-color: #f0f0f0;
  align-self: flex-start;
}

.controls {
  padding: 10px;
  position: relative; /* 使子元素相对定位 */
}

.controls textarea {
  flex-grow: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
  resize: none; /* 禁止调整大小 */
  white-space: pre-wrap; /* 允许换行 */
  overflow-y: auto; /* 溢出时显示滚动条 */
}

.send-icon {
  color: #97a8be;
  position: absolute;
  bottom: 16px; /* 调整距离底部的距离 */
  right: 16px; /* 调整距离右侧的距离 */
  width: 24px; /* 图片宽度 */
  height: 24px; /* 图片高度 */
  cursor: pointer; /* 鼠标悬停时显示指针 */
}

.controls input {
  flex-grow: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.controls button {
  padding: 10px 20px;
  background-color: #1890ff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.draggable-box {
  width: 75px;
  height: 75px;
  background-color: #ffffff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: move;
  position: absolute;
  user-select: none;
}
</style>
